package com.zxy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxy.reggie.common.R;
import com.zxy.reggie.entity.Employee;
import com.zxy.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * @author 周向阳
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录功能
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request , @RequestBody Employee employee){
//        1、将页面提交的数据进行MD5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        System.out.println(password);
//        2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
//        3、调用service 没查到就返回登录失败
        Employee emp = employeeService.getOne(queryWrapper);
        if(emp == null){
            return R.error("未查询到");
        }else if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }else if(emp.getStatus() == 0){
            return R.error("用户已禁用");
        }else {
            request.getSession().setAttribute("employee",emp.getId());
            return R.success(emp);
        }
    }
    /**
     * 登录退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
//        1、清理session中的员工id
        request.getSession().removeAttribute("employee");

        return R.success("退出成功");
    }
    /**
     * 新增员工，
     * @param employee
     * @return
     */
    @PostMapping()
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工:{}",employee.toString() );
//        设置基础密码123456,但要进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        设置创建时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

//        获得当前登录用户的id
//        long emId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(emId);
//        employee.setUpdateUser(emId);
        employeeService.save(employee);

        return R.success("新增员工成功");

    }
    /**
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
//        构建分页构建器
        Page pageInfo = new Page(page,pageSize);
//        构建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
//        添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
//        执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据员工id更改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());

        Long id = Thread.currentThread().getId();
        log.info("当前线程id:{}",id);

//        注意，这里从前端拿到id应该考虑精度问题
//        Long empId = (Long)request.getSession().getAttribute("employee");

//        获取当前时间,以及用户名
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
//        调用employeeService
        employeeService.updateById(employee);

        return R.success("员工信息更新成功");
    }

    /**
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息");
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return R.success(employee);
        }else {
            return R.error("请求出错");
        }

    }

}
